/*
 * Copyright 2015 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.benmei.ntlive.server.netty.socket.handler;

import com.benmei.ntlive.constant.ConnectType;
import com.benmei.ntlive.constant.Constants;
import com.benmei.ntlive.dto.TcpResponse;
import com.benmei.ntlive.server.netty.NetLiveHandler;
import com.benmei.ntlive.service.LiveService;
import com.benmei.ntlive.server.netty.SessionRepository;
import com.benmei.ntlive.utils.ChannelUtil;
import com.benmei.ntlive.utils.JsonUtil;
import io.netty.channel.*;
import io.netty.util.concurrent.ScheduledFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * NtliveServerHandler
 *
 * @author Peter
 * @date 2017-08-17
 */
@Component
@Qualifier("ntliveServerHandler")
@ChannelHandler.Sharable
public class NtliveServerHandler extends ChannelHandlerAdapter {
    private static Logger logger = LoggerFactory.getLogger(NtliveServerHandler.class);

    @Autowired
    private LiveService liveService;

    @Autowired
    private SessionRepository sessionRepository;

    @Autowired
    private NetLiveHandler netLiveHandler;


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.fireChannelActive();
        String client = ctx.channel().remoteAddress().toString();
        logger.debug("A client connect success for {}", client);

        ctx.writeAndFlush(JsonUtil.toJson(new TcpResponse("connect")) + Constants.delimiter);
    }

    /**
     * resive by C.H on 2018/10/29 13:28
     * 修改：
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //消息处理
        netLiveHandler.handler(ctx,msg, ConnectType.SOCKET);

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error(cause.getMessage(), cause);
        ChannelUtil.exitChannelByException(ctx,cause,sessionRepository);
        ctx.close();
        ctx.fireExceptionCaught(cause);
    }


    @Override
    public void channelInactive(ChannelHandlerContext ctx) {

        String channelKey = ctx.channel().remoteAddress().toString();
        // 关闭心跳
        ScheduledFuture<?> heartBeat = sessionRepository.getTaskMap().get(channelKey);
        if (heartBeat != null) {
            logger.info(" \n       / cancel schedule task ------》》》》》》》》" + heartBeat.toString());
            boolean cancelSuccess = heartBeat.cancel(true);

            logger.info("channelInactive: 关闭心跳 for client:" + channelKey + " cancelHeartBeatSuccess:" + cancelSuccess + ", heartBeatInstance" + heartBeat.toString());
            heartBeat = null;
        }
        this.sessionRepository.remove(channelKey);
        /**
         * resive by C.H on 2018/10/29 17:29
         * 增加：sessionRepository.getTaskMap().remove(channelKey)
         */
        sessionRepository.getTaskMap().remove(channelKey);

        logger.info("channelInactive: 移除客户端[{}]后Current room size is {}", channelKey, this.sessionRepository.size());
        // 释放资源
        ctx.close();
        logger.info("channelInactive：释放资源 for client:{}", channelKey);
    }
}
